<?php
declare (strict_types=1);

// +----------------------------------------------------------------------
// | SCApi
// +----------------------------------------------------------------------
// | 版权所有 2021~2022 贾二小 [ http://www.ipsoul.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://www.ipsoul.com
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// | 免费声明 ( http://doc.ipsoul.com/disclaimer )
// +----------------------------------------------------------------------
// | gitee 代码仓库：https://gitee.com/jiaerxiao/scapi
// | github 代码仓库：https://github.com/jiaerxiao/scapi
// +----------------------------------------------------------------------

namespace app\system\service;

use app\common\service\BaseService;
use app\system\enum\LogEnum;
use think\App;

class LogService extends BaseService
{
    /**
     * 初始化 Warning
     * @param App $app
     */
    public function __construct(App $app)
    {
        $this->config['isDelete'] = false;
        $this->config['autoWriteUser'] = false;
        parent::__construct($app, '系统日志', 'log');
    }

    /**
     * 表格数据
     * @author 贾二小
     * @since 2021/11/20
     */
    public function tableList(array $paramData): array
    {
        $map = [];
        if (isset($paramData['type']) && !empty($paramData['type'])) {
            $map[] = ['type', '=', $paramData['type']];
        }
        if (isset($paramData['name']) && !empty($paramData['name'])) {
            $map[] = ['name', 'like', '%' . $paramData['name'] . '%'];
        }
        return $this->table($map);
    }

    /**
     * 插入日志
     * @author 贾二小
     * @since 2022/1/1
     */
    public function insertData(array $data)
    {
        $data['userName'] = $this->userData['userName'] ?? 'System';
        return $this->insertGetId($data);
    }

    /**
     * 图表Option
     * @author 贾二小
     * @since 2022/1/1
     */
    public function chartData(array $paramData): array
    {
        $sql = "SELECT date,type,count(1) as qty FROM sys_log GROUP BY date,type ORDER BY date;";
        $logList = self::query($sql);
        //所有日期
        $xAxisData = array_keys(array_flip(array_column($logList, 'date')));
        return array_map(function ($item) use ($logList) {
            $successQty = 0;
            $warningQty = 0;
            $errorQty = 0;
            foreach ($logList as $vo) {
                if ($item == $vo['date']) {
                    if ($vo['type'] == LogEnum::TYPE_SUCCESS) {
                        $successQty = $vo['qty'];
                    } elseif ($vo['type'] == LogEnum::TYPE_WARNING) {
                        $warningQty = $vo['qty'];
                    } else {
                        $errorQty = $vo['qty'];
                    }
                }
            }
            return ['product' => $item, 'success' => $successQty, 'warning' => $warningQty, 'error' => $errorQty];
        }, $xAxisData);

    }
}